#include "led.h"
#include "FreeRTOS.h"
#include "task.h"
#include "./lcd/bsp_ili9341_lcd.h"
#include "usart.h"
#include "key.h"
#include "stdio.h"
#include "queue.h"
#include "semphr.h"
#include "limits.h"

static TaskHandle_t AppTaskCreate_Handle = NULL;
static TaskHandle_t take_task_handle = NULL;
static TaskHandle_t give_task_handle = NULL;


static void AppTaskCreate(void);
static void Take_Task(void* pvParameters);
static void Give_Task(void* pvParameters);

SemaphoreHandle_t count_sem_handle; 

int main(void)
{ 
	BaseType_t xReturn = pdPASS;
	
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4);//设置系统中断优先级分组4
	KEY_Init();
	LED_Init();		        //初始化LED端口
	ILI9341_Init();//液晶初始化    
	LCD_SetColors(BLACK,WHITE);//设置白底黑字
	LCD_SetFont(&Font8x16);//设置字体大小
	ILI9341_Clear(0,0,LCD_X_LENGTH,LCD_Y_LENGTH);//清屏
  ILI9341_GramScan ( 6 );//设置显示模式
	USART_Config(115200);
  LED_Color(LED_OFF);
	
	xReturn = xTaskCreate((TaskFunction_t )AppTaskCreate,  
                        (const char*    )"AppTaskCreate",
                        (uint16_t       )512, 
                        (void*          )NULL,
                        (UBaseType_t    )1, 
                        (TaskHandle_t*  )&AppTaskCreate_Handle);
	if(pdPASS == xReturn){
		vTaskStartScheduler();          //开启任务调度
	}
  else{
		printf("Error Start RTOS\n");
	}
	
}


static void AppTaskCreate(void)
{
  BaseType_t xReturn = pdPASS;
  
  taskENTER_CRITICAL();   
    
	xReturn = xTaskCreate((TaskFunction_t )Take_Task,  
                        (const char*    )"Take_Task",
                        (uint16_t       )512, 
                        (void*          )NULL,
                        (UBaseType_t    )2, 
                        (TaskHandle_t*  )&take_task_handle);
  if(xReturn != NULL)
	{
		printf("Success Create Take_Task\r\n");
	}
  
	xReturn = xTaskCreate((TaskFunction_t )Give_Task,  
                        (const char*    )"Give_Task",
                        (uint16_t       )512, 
                        (void*          )NULL,
                        (UBaseType_t    )3, 
                        (TaskHandle_t*  )&give_task_handle);
  if(xReturn != NULL)
	{
		printf("Success Create Give_Task\r\n");
	}
	
  vTaskDelete(AppTaskCreate_Handle);
  taskEXIT_CRITICAL();          
}


static void Take_Task(void* pvParameters)
{
	BaseType_t xReturn = pdTRUE;
	uint32_t take_num = pdTRUE;
	while(1)
	{
		if(GET_KEY1){
			take_num = ulTaskNotifyTake(pdFALSE,0);
			if(take_num>0)
				printf("KEY1: Get the park,   ParkingID:%d\n",take_num);
			else
				printf("KEY1: Get the park,   Fulling!!! Press Key2 to free parking\n");
		}
		vTaskDelay(20);
	}
}
static void Give_Task(void* parameter)
{	
  BaseType_t xReturn = pdTRUE;
  while (1)
  {
		if(GET_KEY2){
			xTaskNotifyGive(take_task_handle);
			printf("KEY2: Free a parking\n");
		}
		vTaskDelay(20); 
  }
}
